package com.gmail.avenderov.test.concurrent;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * User: Alexey Venderov
 */
public class IntegerValueHolder implements ValueHolder<Integer> {

    private static final Logger logger = LoggerFactory.getLogger(IntegerValueHolder.class);

    private Integer value;

    @Override    
    public synchronized void put(Integer value) {
        logger.debug("put method called with argument {} by thread: {}", value, Thread.currentThread().getName());
        while (this.value != null) {
            try {
                wait();
            } catch (InterruptedException e) {
                throw new IllegalStateException("Thread " + Thread.currentThread().getName() + " was interrupted.");
            }
        }
        this.value = value;
        notify();
        logger.debug("put method finished.");
    }

    @Override
    public synchronized Integer get() {
        logger.debug("get method called by thread: {}", Thread.currentThread().getName());
        while (this.value == null) {
            try {
                wait();
            } catch (InterruptedException e) {
                throw new IllegalStateException("Thread " + Thread.currentThread().getName() + " was interrupted.");
            }
        }
        final Integer result = this.value;
        this.value = null;
        notify();
        logger.debug("get method finished.");
        return result;
    }
}
